<template>
  <div id="topAnchor">
    <a id="TOPUp" href="#topAnchor">
      <div><i class="el-icon-arrow-up"></i></div>
      <div>TOP</div>
    </a>
    <!-- 表单 -->
    <el-form :label-position="labelPosition" size="small" :model="form" :inline="true" label-width="90px">
      <!-- <el-form-item label="时间 :">
          <el-date-picker v-model="form.createTime" style="width:350px" type="daterange" range-separator="-" start-placeholder="请选择开始日期" end-placeholder="请选择结束日期" format="yyyy 年 MM 月 dd 日"
        value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item> -->
      <el-form-item label="开始时间" style="font-weight:bold;">
        <el-date-picker v-model="form.createTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd" style="width:180px;" clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" style="font-weight:bold;">
        <el-date-picker v-model="form.finishedTime" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd" style="width:180px;" clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item label="校 区" style="font-weight:bold;">
        <el-select v-model="form.campusId" placeholder="请选择校区" style="width:180px;" :disabled="clientRole == 6" clearable>
          <el-option v-for="item in CampusList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼 宇" style="font-weight:bold;">
        <el-select v-model="form.buildId" placeholder="请选择楼宇" style="width:180px;" clearable>
          <el-option v-for="item in buildName" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报修人" style="font-weight:bold;">
        <el-input v-model="form.userName" placeholder="请输入" style="width:180px;" clearable></el-input>
      </el-form-item>
      <el-form-item label="报修类型" style="font-weight:bold;">
        <el-select v-model="form.problemId" placeholder="请选择报修类型" style="width:180px;" clearable>
          <el-option v-for="item in ProblemType" :key="item.id" :label="item.problemName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="维修工" style="font-weight:bold;">
        <el-select v-model="form.workerId" placeholder="请选择维修工" style="width:180px;" clearable>
          <el-option v-for="item in MaintainerList" :key="item.id" :label="item.workerName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="报修状态" style="font-weight:bold;">
        <el-select v-model="form.status" placeholder="请选择报修状态" style="width:180px;" clearable>
          <el-option label="待接单" value="1"></el-option>
          <el-option label="已接单" value="2"></el-option>
          <el-option label="待评价" value="3"></el-option>
          <el-option label="已完成" value="4"></el-option>
          <el-option label="已取消" value="5"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="详细地址" style="font-weight:bold;">
        <el-input v-model="form.detail" placeholder="请输入" style="width:180px;" clearable></el-input>
      </el-form-item>

      <el-form-item label="报修人电话" style="font-weight:bold;">
        <el-input v-model="form.mobile" placeholder="请输入" style="width:180px;" clearable></el-input>
      </el-form-item>
      <el-form-item label="是否转接" style="font-weight:bold;">
        <el-select v-model="form.isTransfer" placeholder="请选择" style="width:180px;" clearable>
          <el-option label="转接单" value="1"></el-option>
          <el-option label="未转接单" value="0"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="buttonList">
      <div class="buttonList_left">
        <!-- <el-button size="small" type="success" icon="el-icon-download" @click="downLoad" plain>下载维修单信息模板</el-button> -->
        <el-button class="exportBtn" size="small" type="success" plain icon="el-icon-download"
          @click="exportForm">导出维修单</el-button>
        <!-- <el-upload action="#" :before-upload="beforeUpload" ref="newuploadin" :show-file-list="false"
          :http-request="uploadHttpRequest" :limit="3" :file-list="fileList">
          <el-button size="small" type="primary" plain icon="el-icon-upload2">导入维修单信息</el-button>
        </el-upload> -->
        <el-button class="exportBtn" size="small" type="success" plain icon="el-icon-download"
          @click="exportTransmit">导出转单记录</el-button>
      </div>
      <div>
        <el-button size="small" class="search_button" type="primary" icon="el-icon-search"
          @click="getDataList">查询</el-button>
        <el-button size="small" class="reset_button" icon="el-icon-refresh" @click="reset">重置</el-button>
      </div>
    </div>



    <el-divider></el-divider>

    <!-- 表格 -->
    <el-table size="medium" ref="multipleTable" :data="tableData" border style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="no" label="报修编号" align="center" width="110"></el-table-column>
      <el-table-column prop="status" label="报修状态" align="center">
        <template slot-scope="scope">
          <span v-if="(scope.row.status == 1)">待接单</span>
          <span v-if="(scope.row.status == 2)">已接单</span>
          <span v-if="(scope.row.status == 3)">待评价</span>
          <span v-if="(scope.row.status == 4)">已完成</span>
          <span v-if="(scope.row.status == 5)">已取消</span>
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="报修人" align="center"></el-table-column>
      <el-table-column prop="userPhone" label="报修人电话" align="center" width="120"></el-table-column>
      <el-table-column prop="campusName" label="校区" align="center"></el-table-column>
      <el-table-column prop="buildName" label="楼宇" align="center"></el-table-column>
      <el-table-column prop="address" label="详细地址" align="center" width="120">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="light" placement="bottom">
            <div slot="content" style="max-width: 600px;font-size:18px">{{ scope.row.address }}</div>
            <div style="text-align:left">
              {{ scope.row.address.length > 10 ? scope.row.address.substr(0, 10) + '...' :
                scope.row.address }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="problemName" label="故障类型" align="center"></el-table-column>
      <el-table-column prop="description" label="问题描述" align="center" width="150">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="light" placement="bottom">
            <div slot="content" style="max-width: 600px;font-size:18px">{{ scope.row.description }}</div>
            <div style="text-align:left">
              {{ scope.row.description.length > 12 ? scope.row.description.substr(0, 12) + '...' :
                scope.row.description }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="appointDate" label="预约日期" align="center" width="110"></el-table-column>
      <el-table-column prop="appointTime" label="预约时间" align="center" width="110"></el-table-column>
      <el-table-column prop="createTime" label="发布时间" align="center" width="170"></el-table-column>
      <el-table-column prop="receiveTime" label="接单时间" align="center" width="170"></el-table-column>
      <el-table-column prop="workerName" label="维修工" align="center"></el-table-column>
      <el-table-column label="操作" align="center"  fixed="right" width="120px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" plain @click="lookDetail({ id: scope.row.id })" icon="el-icon-view" v-if="scope.row.isTransfer == 1"
           >详情</el-button>
           <el-button size="mini" type="text" style="color:red" plain @click="removeDetail({ id: scope.row.id })" icon="el-icon-delete"
           >删除</el-button>
        </template>
         
      </el-table-column>

    </el-table>
    <!-- 表格 -->


    <el-pagination class="pagination" background layout="total, sizes, prev, pager, next, jumper" :total="total"
      :page-size="10" :page-sizes="[10, 20, 30, 40]" @current-change="handleCurrentChange"
      @size-change="handleSizeChange"></el-pagination>


    <el-dialog title="转单详情" :visible.sync="showDetail" width="50%">
      <el-timeline>
        <el-timeline-item icon="el-icon-s-promotion" type="primary" v-for="(item, index) in detail" :key="index"
          :timestamp="item.transferTime">
          <div>转单人：{{ item.transferName }}</div>
          <div>转单人手机号：{{ item.transferPhone }}</div>
          <div>转单原因：{{ item.message }}</div>
          <div>被转单人：{{ item.workerName }}</div>
          <div>被转单人手机号：{{ item.workerPhone }}</div>
        </el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import { getForm, exportForm, downLoad, uploadMaintain, lookDetail, exportTransmit ,delRepairOrder} from '_api/MaintainView/MaintainForm/index.js'
// import { getCampusList } from '_api/DormManage/Campus/index.js'
import { getCampusName, getBuildingName } from '_api/DormManage/Building/index.js'
import { getProblemType } from '_api/MaintainView/MaintainType/index.js'
import { getMaintainerList } from '_api/UserManage/Maintainer/index.js'
export default {
  data() {
    return {
      clientRole: "",
      labelPosition: "right",
      form: {
        campusId: "",
        buildId: "",
        createTime: "",
        current: 0,
        field: "",
        finishedTime: "",
        order: "",
        pageSize: 10,
        problemId: "",
        status: "",
        workerId: "",
        userName: "",
        detail: "",
        mobile: "",
        isTransfer: ""
      },
      tableData: [],
      CampusList: [],
      buildName: [],
      ProblemType: [],
      MaintainerList: [],
      timeNow: "",
      total: 0,
      fileList: [],
      showDetail: false,
      detail: [],
      multipleSelection: []
    }
  },
  watch: {
    form: {
      // 执行方法
      handler(oldValue, newValue) {
        getBuildingName({ campusId: newValue.campusId, type: 1 }).then(res => {
          if (res.status == 200) {
            this.buildName = res.data.data
          }
        })
      },
      deep: true, // 深度监听
      // immediate: true  // 第一次改变就执行
    }
  },

  methods: {
    // 导出转单
    exportTransmit() {
      if (this.multipleSelection.length == 0) {
        this.$message.warning('请先勾选需要导出的数据！')
        return false
      }
      exportTransmit(this.multipleSelection).then(res => {
        const link = document.createElement('a')  //创建a标签
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) //设置文件流
        link.style.display = 'none'// 设置连接
        link.href = URL.createObjectURL(blob)  //将文件流转化为blob地址
        this.getCurrentTime()
        link.download = '转单记录_' + this.timeNow
        document.body.appendChild(link) // 模拟点击事件
        link.click()  //设置点击事件
        this.$message.success('下载成功！')
      })
    },
    handleSelectionChange(val) {
      // console.log(val);
      val.forEach(item => {
        if (!this.multipleSelection.includes(item.id)) {
          this.multipleSelection.push(item.id)
        }
      })
      if (val.length == 0) {
        this.multipleSelection = []
      }
      console.log(this.multipleSelection);
    },
    lookDetail(e) {
      lookDetail(e).then(res => {
        if (res.data.success == true) {
          this.showDetail = true
          this.detail = res.data.data
        }
      })
    },
    // 删除
    removeDetail(e) {
      console.log(e);
      this.$confirm('此操作将删除该保修单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRepairOrder(e).then(res => {
          if (res.status == 200) {
            this.$message({
              message: '删除成功!',
              duration: 1000,
              type: 'success',
              onClose: () => {
                this.reset()
              }
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //重置
    reset() {
      if (this.clientRole == 6) {
        this.form.current = 0
        this.form.pageSize = 10
        this.form.createTime = ""
        this.form.finishedTime = ""
        this.form.problemId = ""
        this.form.status = ""
        this.form.workerId = ""
        this.form.detail = ""
        this.form.mobile = ""

      } else {
        this.form = {
          campusId: "",
          createTime: "",
          current: 0,
          field: "",
          finishedTime: "",
          order: "",
          pageSize: 10,
          problemId: "",
          status: "",
          workerId: "",
          detail: "",
          mobile: ""
        }
      }
      this.getForm()
    },
    getCurrentTime() {
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
      _this.gettime = yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss;
      console.log(_this.gettime)
      this.timeNow = _this.gettime
    },
    // 下载模板
    downLoad() {
      downLoad().then(res => {
        const link = document.createElement('a')  //创建a标签
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) //设置文件流
        link.style.display = 'none'// 设置连接
        link.href = URL.createObjectURL(blob)  //将文件流转化为blob地址
        this.getCurrentTime()
        link.download = '维修单模板_' + this.timeNow
        document.body.appendChild(link) // 模拟点击事件
        link.click()  //设置点击事件
        this.$message.success('下载成功！')
      })
    },
    //导出维修单信息
    exportForm() {
      exportForm(this.form).then(res => {
        const link = document.createElement('a')  //创建a标签
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) //设置文件流
        link.style.display = 'none'// 设置连接
        link.href = URL.createObjectURL(blob)  //将文件流转化为blob地址
        this.getCurrentTime()
        link.download = '维修单统计报表_' + this.timeNow
        document.body.appendChild(link) // 模拟点击事件
        link.click()  //设置点击事件
        this.$message.success('导出成功！')

        // let dis = res.headers["content-disposition"]
        // console.log(dis,"12121212121212121");
        // let fileName = dis.split('attachment;filename=')[1]
        // fileName=decodeURIComponent(fileName)
        // console.log(fileName)
      })
    },
    beforeUpload(file) {
      // 校验
      let legalName = ["xlsx", "xls"];
      // 拿到后缀名
      let name = file.name.substring(
        file.name.lastIndexOf(".") + 1,
        file.name.length
      );
      if (legalName.includes(name)) {
      } else {
        this.$message.info("文件格式不对,仅限xls和xlsx");
        return false;
      }
    },
    // 导入维修单信息
    uploadHttpRequest(data) {
      let fd = new FormData()
      fd.append('file', data.file)
      uploadMaintain(fd).then(res => {
        if (res.data.success == true) {
          this.$message.success("导入成功！")
          this.reset()
        } else {
          this.$message({
            message: res.data.message,
            duration: 3000
          })
        }
      })

    },
    handleCurrentChange(e) {
      //当前页
      this.form.current = (e - 1) * 10
      this.getForm()
    },
    handleSizeChange(e) {
      this.form.pageSize = e
      this.getForm()

    },
    // 查询按钮
    getDataList() {
      this.form.current = 0
      this.getForm()
    },
    //查询维修单信息
    getForm() {
      getForm(this.form).then(res => {
        console.log(res)
        if (res.data.success == true) {
          this.tableData = res.data.data.list
          this.total = res.data.data.total
        } else {
          this.tableData = res.data.data
          this.total = ""
          this.$message.info(res.data.message)
        }
      })
    },
    //查询校区名称
    getCampusName() {
      getCampusName().then(res => {
        console.log(res)
        if (res.status == 200) {
          this.CampusList = res.data.data
          this.CampusList.forEach(item => {
            if (item.name == window.localStorage.getItem('campusName')) {
              if (this.clientRole == 6) {
                this.form.campusId = item.id
              }
            }
          })
          this.getForm()
          this.getProblemType()
          this.getMaintainerList()
          this.getBuildingName()
        }
      })
    },
    //获取楼宇名称
    getBuildingName() {
      getBuildingName({ campusId: this.form.campusId, type: 1 }).then(res => {
        // console.log(res)
        if (res.status == 200) {
          this.buildName = res.data.data
        }
      })
    },
    //查询故障类型
    getProblemType() {
      getProblemType({
        current: 0,
        field: "",
        order: "",
        pageSize: 100
      }).then(res => {
        console.log(res)
        if (res.status == 200) {
          this.ProblemType = res.data.data.list
        }
      })
    },
    //查询维修工列表
    getMaintainerList() {
      getMaintainerList(
        {
          current: 0,
          deptId: "",
          field: "",
          name: "",
          order: "",
          pageSize: 100,
          type: ""
        }
      ).then(res => {
        console.log(res)
        if (res.status == 200) {
          this.MaintainerList = res.data.data.list
        }
      })
    },
  },
  created() {
    // this.getForm()
    this.clientRole = window.localStorage.getItem('clientRole')
    this.getCampusName()
    // this.getProblemType()
    // this.getMaintainerList()
    // this.getBuildingName()
  },
};
</script>
<style lang="scss" scoped>
#TOPUp {
  position: fixed;
  right: 45px;
  bottom: 100px;
  width: 40px;
  height: 40px;
  z-index: 99999999;
  box-shadow: 0px 0px 4px 4px #ecefef;
  border-radius: 20px;
  font-size: 14px;
  text-decoration-line: none;
  text-align: center;
}

.backTop {

  cursor: pointer;
}

.buttonList {
  display: flex;
  width: 80%;
  justify-content: space-between;
}

.buttonList_left {
  display: flex;
  width: 24%;
  justify-content: space-around;
}

.exportBtn {
  // margin-left: 90px;
}

.search_button {
  // margin-left: 30px;
}

.reset_button {
  margin-left: 10px;
}

// .delete_button{
//   margin-left: 10px;
// }
.dialogbutton {
  margin-right: 40%;
}

.pagination {
  float: right;
  margin-top: 10px;
}
</style>
